package gnss

import (
	"time"
)

type GnssRtcmAna struct {
	StartT         time.Time
	LatestMsmT     time.Time
	LatestMsm      *RtcmRawMsmObs
	rtcmRaw        *Rtcm3RawBuf
	DelayCheckFlag int
	OnRtcmErr      func(errcode int, err error) bool
	OnRtcmPosi     func(sta *GnssStation, buf []byte)
	OnRtcm1033     func(rec *Gnss1033Rec, buf []byte)
	OnRtcmMsm      func(rec *RtcmRawMsmObs, buf []byte)

	// 观测值
	OnRtcmMsmBuf func(buf []byte)
}

func NewGnssRtcmAna() *GnssRtcmAna {
	rval := &GnssRtcmAna{
		DelayCheckFlag: 1,
		rtcmRaw:        NewRtcm32RawBuf(""),
	}
	rval.rtcmRaw.OnErr = func(errcode int, err error) bool {
		if rval.OnRtcmErr != nil {
			return rval.OnRtcmErr(errcode, err)
		}
		return true
	}
	rval.rtcmRaw.OnRtcmBuf = func(rtcmBuf []byte) {
		msgid := uint16(GetRtcmMsgId(rtcmBuf, 24))
		if (msgid == 1005 || msgid == 1006) && rval.OnRtcmPosi != nil {
			rec := &GnssStation{}
			DecodeRtcm1005V1(rec, rtcmBuf, 24)
			rval.OnRtcmPosi(rec, rtcmBuf)
		} else if msgid == 1033 && rval.OnRtcm1033 != nil {
			rec := &Gnss1033Rec{}
			DecodeRtcm1033(rec, rtcmBuf, 24)
			rval.OnRtcm1033(rec, rtcmBuf)
		} else {

			if RtcmIsMsm4(msgid) {
				if rval.OnRtcmMsm != nil {
					rawObs := &RtcmRawMsmObs{}
					rval.LatestMsm = rawObs
					msm := NewRtcmRawMsm4()
					msm.DecodeMsm(rtcmBuf)
					//tow = msm.Header.GetTOW()
					rawObs.Header.CopyInfoFrom(&msm.Header)
					msm.WriteToObs(rawObs)
					rval.OnRtcmMsm(rawObs, rtcmBuf)
				}

				if rval.OnRtcmMsmBuf != nil {
					rval.OnRtcmMsmBuf(rtcmBuf)
				}
			} else if RtcmIsMsm7(msgid) {
				if rval.OnRtcmMsm != nil {
					rawObs := &RtcmRawMsmObs{}
					rval.LatestMsm = rawObs
					msm := NewRtcmRawMsm7()
					msm.DecodeMsm(rtcmBuf)
					//tow = msm.Header.GetTOW()
					rawObs.Header.CopyInfoFrom(&msm.Header)
					msm.WriteToObs(rawObs)
					rval.OnRtcmMsm(rawObs, rtcmBuf)
				}

				if rval.OnRtcmMsmBuf != nil {
					rval.OnRtcmMsmBuf(rtcmBuf)
				}
			}

		}

	}
	return rval
}

func (this *GnssRtcmAna) InputBuf(buf []byte) {
	this.rtcmRaw.InputBlockBuf(buf)
}
